package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Sound;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author WZQ
 * @date 2022/1/6
 * @TIME:20:12
 */
@DubboService
public class PeachBlossomApiImpl implements PeachBlossomApi {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public void save(String videoUrl, Long userId) {
        Sound sound = new Sound();
        sound.setId(new ObjectId());
        sound.setUserId(userId);
        sound.setSoundUrl(videoUrl);
        sound.setIsUse(1);
        mongoTemplate.save(sound);

    }

    @Override
    public Sound randomSound(Long userId) {
        // 随机查询未使用过的语音
        try {
            Criteria criteria = Criteria.where("isUse").is(1).and("userId").nin(userId);
            Query query = Query.query(criteria);
            long count = mongoTemplate.count(query, Sound.class);
            if (count == 0) {
                throw new RuntimeException("没有更新的语音啦");
            }
            TypedAggregation aggregation = Aggregation.newAggregation(Sound.class, Aggregation.match(criteria), Aggregation.sample(1));
            AggregationResults<Sound> aggregate = mongoTemplate.aggregate(aggregation, Sound.class);
            List<Sound> mappedResults = aggregate.getMappedResults();
            ObjectId soundId = mappedResults.get(0).getId();
            // 查询完毕修改状态
            query = new Query(Criteria.where("id").is(soundId));
            Update update = new Update();
            update.inc("isUse", 1);
            mongoTemplate.updateFirst(query, update, Sound.class);
            return mappedResults.get(0);
        } catch (Exception e) {
            throw new RuntimeException("系统繁忙请稍微再试");
        }
    }
}
